package com.zhao.fishingguideserver.utils;

import com.zhao.fishingguideserver.exception.BusinessException;

import java.util.Map;

/**
 * 用户上下文工具类
 * 统一处理从ThreadLocal获取用户信息的逻辑
 */
public class UserContextUtil {
    
    /**
     * 获取当前登录用户ID
     * @return 用户ID
     * @throws BusinessException 如果用户未登录或ID格式错误
     */
    public static Integer getCurrentUserId() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            throw new BusinessException("用户未登录");
        }
        try {
            return Integer.parseInt(claims.get("id").toString());
        } catch (NumberFormatException e) {
            throw new BusinessException("用户ID格式错误");
        }
    }
    
    /**
     * 获取当前登录管理员ID
     * @return 管理员ID
     * @throws BusinessException 如果管理员未登录或ID格式错误
     */
    public static Integer getCurrentAdminId() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("adminId") == null) {
            throw new BusinessException("管理员未登录");
        }
        try {
            return Integer.parseInt(claims.get("adminId").toString());
        } catch (NumberFormatException e) {
            throw new BusinessException("管理员ID格式错误");
        }
    }
    
    /**
     * 获取当前登录用户名
     * @return 用户名
     * @throws BusinessException 如果用户未登录
     */
    public static String getCurrentUsername() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("username") == null) {
            throw new BusinessException("用户未登录");
        }
        return claims.get("username").toString();
    }
    
    /**
     * 尝试获取当前用户ID，如果未登录返回null而不抛出异常
     * @return 用户ID或null
     */
    public static Integer getCurrentUserIdSafely() {
        try {
            Map<String, Object> claims = ThreadLocalUtil.get();
            if (claims == null || claims.get("id") == null) {
                return null;
            }
            return Integer.parseInt(claims.get("id").toString());
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取完整的用户信息
     * @return 用户信息Map
     * @throws BusinessException 如果用户未登录
     */
    public static Map<String, Object> getCurrentUserClaims() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null) {
            throw new BusinessException("用户未登录");
        }
        return claims;
    }
}
